package sf.view.fields;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JLabel;
import javax.swing.JTextField;

import sf.model.fields.AbstractFieldModel;
import sf.model.fields.DateFieldModel;
import sf.model.fields.event.FieldChangeEvent;

public class DateField extends AbstractField
{

	private static final long serialVersionUID = 4605462275675499709L;

	private class DateFieldController implements ActionListener, FocusListener
	{

		
		public void actionPerformed(ActionEvent e)
		{
			updateValue();
		}

		
		public void focusGained(FocusEvent e)
		{
			// TODO Auto-generated method stub

		}

		
		public void focusLost(FocusEvent e)
		{
			updateValue();
		}

		private void updateValue()
		{
			if (((DateFieldModel) getModel()).check(inputField.getText())
					&& !inputField.getText().equals(getModel().getValue()))
			{
				model.setValue(inputField.getText());
			}
		}

	}

	private DateFieldModel model;
	private DateFieldController controller;

	private JTextField inputField;

	public DateField()
	{
		setModel(new DateFieldModel());
		controller = new DateFieldController();

		JLabel label = new JLabel(getLabelText());
		add(label, BorderLayout.WEST);

		inputField = new JTextField();
		inputField.addActionListener(controller);
		inputField.addFocusListener(controller);

		model.setPatternByString(""); // FIXME
	}

	
	public AbstractFieldModel getModel()
	{
		return model;
	}

	
	public Object getValue()
	{
		return model.getValue();
	}

	
	public void setModel(AbstractFieldModel model)
	{
		this.model = (DateFieldModel) model;
		this.model.addChangeListener(this);
		inputField.setText((String) this.model.getValue());
	}

	
	public void setValue(Object value)
	{
		model.setValue(value);
	}

	
	public void changePerformed(FieldChangeEvent event)
	{
		inputField.setText((String) model.getValue());
	}

	
	public void setEditable(boolean editable)
	{
		// TODO Auto-generated method stub

	}

}
